package com.googlecode.bluetools.common.security;

/**
 * 
 */
public class ByteUtil {

	/**
	 * Returns a byte array containing the two's-complement representation of the integer.<br>
	 * The byte array will be in big-endian byte-order with a fixes length of 4 (the least significant byte is in the
	 * 4th element).<br>
	 * <br>
	 * <b>Example:</b><br>
	 * <code>intToByteArray(258)</code> will return { 0, 0, 1, 2 },<br>
	 * <code>BigInteger.valueOf(258).toByteArray()</code> returns { 1, 2 }.
	 * 
	 * @param integer The integer to be converted.
	 * @return The byte array of length 4.
	 */
	public static final byte[] intToByteArray(int integer) {
		byte[] dword = new byte[4];
		dword[0] = (byte) ((integer >> 24) & 0x000000FF);
		dword[1] = (byte) ((integer >> 16) & 0x000000FF);
		dword[2] = (byte) ((integer >> 8) & 0x000000FF);
		dword[3] = (byte) (integer & 0x00FF);
		return dword;

	}

	/**
	 * Return a integer <br>
	 * The byte array will be in big-endian byte-order with a fixes length of 4 (the least significant byte is in the
	 * 4th element).</br>
	 * 
	 * @param b
	 * @return
	 */
	public static final int byteArrayToInt(byte[] b) {
		return b[0] << 24 | (b[1] & 0xff) << 16 | (b[2] & 0xff) << 8 | (b[3] & 0xff);
	}
}
